package com.gong.yuanma.lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author GongChang
 * @version 1.0
 * @date 2021/6/13 0013 22:36
 */
public class ReadWriteLockDemo {

    volatile Map<String,Object> map = new HashMap<>();
    private ReadWriteLock rl = new ReentrantReadWriteLock();

    //写
    public void push(String key,Object o){
        rl.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"正在写"+key);
            try {
                TimeUnit.MILLISECONDS.sleep(5);
            } catch (Exception e) {
                e.printStackTrace();
            }
            map.put(key,o);
            System.out.println(Thread.currentThread().getName()+"写完成");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            rl.writeLock().unlock();
        }

    }

    //读
    public void get(String key){
        rl.readLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+"正在读");
            Object o = map.get(key);
            System.out.println(Thread.currentThread().getName()+"读完成："+o);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            rl.readLock().unlock();
        }

    }

    public static void main(String[] args) {
        ReadWriteLockDemo rd = new ReadWriteLockDemo();

        for (int i = 0; i < 5; i++) {
            final int s = i;
            new Thread(()->{
                rd.push("第"+s,s);
            },"a"+s).start();
        }

        for (int i = 0; i < 5; i++) {
            final int s = i;
            new Thread(()->{
                rd.get("第"+s);
            },"b"+s).start();
        }
    }
}
